package com.example.exam.utils;

import cn.hutool.core.net.NetUtil;
import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import com.example.exam.pojo.MyUserAgent;
import com.google.common.net.HttpHeaders;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * @author zhozixiong
 * @date 2023/07/03
 */
public class HttpUtil extends cn.hutool.http.HttpUtil {

    private static final String[] LOCALHOST = {"unknown", "127.0.0.1", "0:0:0:0:0:0:0:1"};

    private HttpUtil() {

    }

    public static HttpServletRequest getHttpServletRequest() {
        return ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
    }

    public static String getHeader(String key) {
        return getHttpServletRequest().getHeader(key);
    }

    /**
     * 获取请求ip
     * @return ip地址
     */
    public static String getIpAddress() {
        HttpServletRequest request = getHttpServletRequest();
        String ip = request.getHeader(HttpHeaders.X_FORWARDED_FOR);
        if (ip == null || ip.length() == 0 || LOCALHOST[0].equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || LOCALHOST[0].equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if(ip == null || ip.length() == 0 || LOCALHOST[0].equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if(ip == null || ip.length() == 0 || LOCALHOST[0].equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || LOCALHOST[0].equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        System.out.println(ip);
        if (LOCALHOST[0].equalsIgnoreCase(ip) || LOCALHOST[1] .equalsIgnoreCase(ip) || LOCALHOST[2].equalsIgnoreCase(ip)) {
            ip = NetUtil.getLocalhostStr();
        }
        return ip;
    }

    /**
     * 获取用户浏览器信息
     * @return 浏览器信息
     */
    public static MyUserAgent getUserAgent() {
        String userAgent = getHeader(HttpHeaders.USER_AGENT);
        UserAgent parse = UserAgentUtil.parse(userAgent);
        return new MyUserAgent(parse.getBrowser().getName() + " " + parse.getVersion(), parse.getOs().getName());
    }

    /**
     * 获取请求路径
     * @return 请求路径
     */
    public static String getRequestUrl() {
        return getHttpServletRequest().getRequestURI();
    }
}
